//
//  ScencScreenWND.m
//  SMTools
//
//  Created by fengsh on 2019/1/14.
//  Copyright © 2019年 fengsh. All rights reserved.
//

#import "ScencScreenWND.h"
#import <Masonry/Masonry.h>
#import "SceneCardView.h"
#import "SMPrizeTitleView.h"
#import <QuartzCore/QuartzCore.h>
#import "ScencMembers.h"
#import "ScencResults.h"
#import <MagicalRecord/MagicalRecord.h>

@interface ScencScreenWND ()<NSWindowDelegate>
///背景图
@property (weak) IBOutlet NSImageView                               *imgv_bg;
///随机显示的区域
@property (weak) IBOutlet NSView                                    *random_v;
@property (weak) IBOutlet NSView                                    *congratulations_v;
@property (weak) IBOutlet NSView                                    *operator_v;
@property (nonatomic, strong) NSTimer                               *timer;
@property (nonatomic, strong) NSMutableArray                        *dataset;
///每个卡片的大小
@property (nonatomic, assign) CGSize                                card_size;
@property (nonatomic, strong) SMPrizeTitleView                      *titleview;
///显示的卡片数量
@property (nonatomic, assign) NSInteger                             cardcount;
///一批中奖的索引
@property (nonatomic, strong) NSMutableArray                        *luckyIndexs;
///当前轮次是否抽完了
@property (nonatomic, assign) BOOL                                  isfinish;

@end

@implementation ScencScreenWND

- (void)windowDidLoad {
    [super windowDidLoad];
    
    self.dataset = [NSMutableArray array];
    self.luckyIndexs = [NSMutableArray array];
    
    _isfinish = NO;
    ///每轮中奖人数
    NSInteger ns = self.currentprize.prize_nums_per;
    ///现有的参与人数
    NSInteger nowms = self.joinmembers.count;
    ///因为一屏最大只能显示10个，所以不要多了啊，显示不下
    self.cardcount = MIN(10,MIN(ns,nowms));
    
    if (_style == ScreenStyleWideScreen) {
        [self generate4_1ScreenUI];
    }
    
    ///一开始是隐藏的
    self.random_v.hidden = YES;
    
    [self.titleview.lb_title setStringValue:self.currentprize.prizeName];
    if (self.currentprize.prize_total_count > 1) { //显示轮次
        NSInteger rc = (self.currentprize.prize_total_count - self.currentprize.prize_remain_count)+1;
        [self.titleview.subTitle setStringValue:[NSString stringWithFormat:@"第%ld轮,每轮%hd名",rc,self.currentprize.prize_nums_per]];
    }
}

- (void)dealloc
{
    NSLog(@"ScencScreenWND Free.");
}

- (void)keyDown:(NSEvent *)event
{

}

- (void)keyUp:(NSEvent *)event
{
    NSUInteger code = event.keyCode;
    if (code == 36) { //回车键
        if (!_timer) {
            [self start]; //按一下开始，再按一下停止
        } else {
            [self userstop];
        }
    } else if (code == 49) {
        ///本想直接进入下一轮，但还得移除中奖的逻辑
    } else if (code == 53) { //关闭
        [self close];
    }
    NSLog(@"event = %@",event);
}


- (void)start
{
    if (_isfinish) { ///本次已经操完了
        return;
    }
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.050f target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
        self.random_v.hidden = NO;
    }
}

- (void)stop
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)userstop
{
    [self stop];
    
    _isfinish = YES;
    
    [self makeFireworksDisplay];
    
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        NSDate *dt = [NSDate date];
        for (NSNumber *idx in self.luckyIndexs) {
            ScencMembers *luck = self.joinmembers[[idx integerValue]];
            
            ScencResults *ret = [ScencResults MR_createEntityInContext:localContext];
            ret.memberid = luck.mid;
            ret.name = luck.name;
            ret.mobile = luck.mobile;
            ret.department = luck.department;
            ret.prizeNo = self.currentprize.prizeNo;
            ret.prizeName = self.currentprize.prizeName;
            ret.prizeInCount = (self.currentprize.prize_total_count - self.currentprize.prize_remain_count + 1);
            ret.createTime = dt;
        }
        ///更新当前操作的
        ScenePrizes *updateprize = [ScenePrizes MR_findFirstByAttribute:@"prizeNo" withValue:self.currentprize.prizeNo inContext:localContext];
        updateprize.prize_remain_count -= 1;
        self.currentprize.prize_remain_count -= 1;

    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        NSLog(@"保存 %d,error = %@",contextDidSave,error);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"kOpenLuckyFinish" object:nil];
    }];
}

- (NSInteger)getUniqueIdx
{
    ///现有的参与人数
    NSInteger nowms = self.joinmembers.count;
    NSInteger idx = (arc4random()%nowms);
    if ([self.luckyIndexs containsObject:@(idx)]) {
        NSLog(@"有重复 idx = %ld",(long)idx);
        return [self getUniqueIdx];
    }
    return idx;
}

- (void)onTimer:(NSTimer *)timer
{
    NSLog(@"===========");
    ///显示到卡片
    [self.luckyIndexs removeAllObjects];
    
    for (SceneCardView *item in self.dataset) {
        NSInteger idx = [self getUniqueIdx];
        NSLog(@"随机idx = %ld",idx);
        [self.luckyIndexs addObject:@(idx)];
        ScencMembers *mb = self.joinmembers[idx];
        [item.lb_name setStringValue:mb.name];
        [item.lb_department setStringValue:mb.department];
    }
}

- (BOOL)windowShouldClose:(NSWindow *)sender
{
    [self stop];
    return YES;
}

#pragma mark - UI处理
- (void)generate4_1ScreenUI
{
    //    float scale = [NSScreen mainScreen].backingScaleFactor;
    //    scale *= 2.0;
    
    float sw = CGRectGetWidth([NSScreen mainScreen].frame);
    //    float sh = CGRectGetHeight([NSScreen mainScreen].frame);
    
    NSImage *img = [NSImage imageNamed:@"img_back4_1.jpg"];
    self.imgv_bg.image = img;
    //    float w = img.size.width / scale;
    //    float h = img.size.height / scale;
    
    //取当前屏幕的 3/4 来做 4 : 1 显示
    float w = floor(sw * 0.9);
    float h = floor(w * 0.25);
    
    CGSize sz = CGSizeMake(w, h);
    
    [self.window setContentSize:sz];
    //2倍图
    [self.imgv_bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(@(0));
        make.width.equalTo(@(sz.width));
        make.height.equalTo(@(sz.height));
    }];
    
    [self.random_v mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@(0));
    }];
    
    float cw = w * 0.16;
    float ch = w * 0.07;
    
    self.card_size = CGSizeMake(cw, ch);
    
    NSInteger totals = self.cardcount;
    
    ///换一行一组
    NSMutableArray *rows = [NSMutableArray array];
    ///每行最大5个
    NSMutableArray *row = nil;
    ///重置
    [self.dataset removeAllObjects];
    ///清空
    [self.random_v.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    if (totals <= 5) {
        row = [NSMutableArray array];
        [rows addObject:row];
        for (NSInteger i = 1; i <= totals; i++) {
            SceneCardView *item = [[SceneCardView alloc]init];
            [self.random_v addSubview:item];
            ///用于排版
            [row addObject:item];
            ///用于刷新
            [self.dataset addObject:item];
        }
    } else {
        if ((totals % 2) == 0) { //平分
            NSInteger t = totals / 2;
            for (NSInteger i = 1; i <= totals; i++) {
                SceneCardView *item = [[SceneCardView alloc]init];
                [self.random_v addSubview:item];
                if (!row) {
                    row = [NSMutableArray array];
                    [rows addObject:row];
                }
                ///用于排版
                [row addObject:item];
                ///用于刷新
                [self.dataset addObject:item];
                
                if ((i % t) == 0) {
                    row = nil;
                }
            }
        } else { //单数的则每行填满，剩余的放新行
            for (NSInteger i = 1; i <= totals; i++) {
                SceneCardView *item = [[SceneCardView alloc]init];
                [self.random_v addSubview:item];
                if (!row) {
                    row = [NSMutableArray array];
                    [rows addObject:row];
                }
                ///用于排版
                [row addObject:item];
                ///用于刷新
                [self.dataset addObject:item];
                
                if ((i % 5) == 0) {
                    row = nil;
                }
            }
        }
    }
    
    /**
     *  axisType         轴线方向
     *  fixedSpacing     间隔大小(视两边间隔距而定的) 所以有时候看起来不起效果
     *  fixedItemLength  每个控件的固定长度/宽度
     *  leadSpacing      头部间隔
     *  tailSpacing      尾部间隔
     */
    
    NSLog(@"rows = %@",rows);
    NSInteger itemcount = self.dataset.count;
    if (itemcount > 1) {
        
        if (rows.count > 1) { // 两行
            ///竖直
            float top = 20;
            float spacing_y = 10;//
            
            float row_one_offsety = -((spacing_y + ch) / 2.0) + top;
            float row_two_offsety = ((spacing_y + ch) / 2.0) + top;
            
            
            for (NSInteger j = 0; j < rows.count ;j++) {
                
                NSInteger rowcount = ((NSArray *)rows[j]).count;
                float item_total_w = cw * rowcount;
                ///每个间隔50
                float spacing = -20;
                ///剩下的宽度
                float remain_w = (w - item_total_w) - spacing * (rowcount - 1) ;
                
                float side_w = remain_w / 2.0;
                
                [rows[j] mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:spacing leadSpacing:side_w tailSpacing:side_w];
                
                [rows[j] mas_makeConstraints:^(MASConstraintMaker *make) {
                    if (j == 0) {
                        make.centerY.equalTo(@(0)).offset(row_one_offsety);
                    } else {
                        make.centerY.equalTo(@(0)).offset(row_two_offsety);
                    }
                    make.width.equalTo(@(cw));
                    make.height.equalTo(@(ch));
                }];
            }
        } else { //1行
            //卡片占的长度
            float item_total_w = cw * itemcount;
            ///每个间隔50
            float spacing = -20;
            ///剩下的宽度
            float remain_w = (w - item_total_w) - spacing * (itemcount - 1) ;
            
            float side_w = remain_w / 2.0;
            
            [rows[0] mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:spacing leadSpacing:side_w tailSpacing:side_w];
            
            [rows[0] mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(@(0));
                make.width.equalTo(@(cw));
                make.height.equalTo(@(ch));
            }];
        }
    } else if (itemcount == 1) {
        [self.dataset[0] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(@(0));
            make.width.equalTo(@(cw));
            make.height.equalTo(@(ch));
        }];
    }
    
    ////标题
    self.titleview = [[SMPrizeTitleView alloc]init];
    
    [self.congratulations_v addSubview:self.titleview];
    
    [self.titleview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(20));
        make.leading.equalTo(@(30));
        make.trailing.equalTo(@(-30));
        make.height.equalTo(@(90));
    }];
    
    ///烟花
    [self.congratulations_v mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@(0));
    }];
    
    ///操作区
    [self.operator_v mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@(0));
    }];
}

/*
 CAEmitterLayer 可能用到是属性
 * birthRate:粒子产生系数，默认1.0；
 * emitterCells: 装着CAEmitterCell对象的数组，被用于把粒子投放到layer上；
 * emitterDepth:决定粒子形状的深度联系：emittershape
 * emitterMode:发射模式
 * emitterPosition:发射位置
 * emitterShape:发射源的形状;
 * emitterSize:发射源的尺寸大；
 * emitterZposition:发射源的z坐标位置；
 * lifetime:粒子生命周期
 * preservesDepth:不是多很清楚（粒子是平展在层上）
 * renderMode:渲染模式：
 * scale:粒子的缩放比例：
 * seed：用于初始化随机数产生的种子
 * spin:自旋转速度
 * velocity：粒子速度
 
 
 //CAEmitterCell 可能用到的属性
 * birthRate 这个必须要设置，具体含义是每秒某个点产生的effectCell数量
 * alphaRange:  一个粒子的颜色alpha能改变的范围；
 * alphaSpeed:粒子透明度在生命周期内的改变速度；
 * blueRange：一个粒子的颜色blue 能改变的范围；
 * blueSpeed: 粒子blue在生命周期内的改变速度；
 * color:粒子的颜色
 * contents：是个CGImageRef的对象,既粒子要展现的图片；
 * contentsRect：应该画在contents里的子rectangle：
 * emissionLatitude：发射的z轴方向的角度
 * emissionLongitude:x-y平面的发射方向
 * emissionRange；周围发射角度
 * emitterCells：粒子发射的粒子
 * enabled：粒子是否被渲染
 * greenrange: 一个粒子的颜色green 能改变的范围；
 * greenSpeed: 粒子green在生命周期内的改变速度；
 * lifetime：生命周期
 * lifetimeRange：生命周期范围
 * magnificationFilter：不是很清楚好像增加自己的大小
 * minificatonFilter：减小自己的大小
 * minificationFilterBias：减小大小的因子
 * name：粒子的名字
 * redRange：一个粒子的颜色red 能改变的范围；
 * redSpeed; 粒子red在生命周期内的改变速度；
 * scale：缩放比例：
 * scaleRange：缩放比例范围；
 * scaleSpeed：缩放比例速度：
 * spin：子旋转角度
 * spinrange：子旋转角度范围
 * style：不是很清楚：
 * velocity：速度
 * velocityRange：速度范围
 * xAcceleration:粒子x方向的加速度分量
 * yAcceleration:粒子y方向的加速度分量
 * zAcceleration:粒子z方向的加速度分量
 
 */
#pragma mark - 粒子处理
//开奖后祝贺效果
- (void)makeFireworksDisplay {
    // 粒子发射系统 的初始化
    CAEmitterLayer *fireworksEmitter = [CAEmitterLayer layer];
    CGRect viewBounds = self.congratulations_v.bounds;
    // 发射源的位置
    fireworksEmitter.emitterPosition = CGPointMake(viewBounds.size.width/2.0, viewBounds.size.height);
    // 发射源尺寸大小
    fireworksEmitter.emitterSize = CGSizeMake(viewBounds.size.width/2.0, 0.0);
    // 发射模式
    fireworksEmitter.emitterMode = kCAEmitterLayerOutline;
    // 发射源的形状
    fireworksEmitter.emitterShape = kCAEmitterLayerLine;
    // 发射源的渲染模式
    fireworksEmitter.renderMode = kCAEmitterLayerAdditive;
    // 发射源初始化随机数产生的种子
    fireworksEmitter.seed = (arc4random()%100)+1;
    
    /**
     *  添加发射点
     一个圆（发射点）从底下发射到上面的一个过程
     */
    CAEmitterCell* rocket  = [CAEmitterCell emitterCell];
    rocket.birthRate = 1.0; //是每秒某个点产生的effectCell数量
    rocket.emissionRange = 0.25 * M_PI; // 周围发射角度
    rocket.speed = 1;
    rocket.velocity = 400; // 速度
    rocket.velocityRange = 100; // 速度范围
    rocket.yAcceleration = 75; // 粒子y方向的加速度分量
    rocket.lifetime = 1.02; // effectCell的生命周期，既在屏幕上的显示时间要多长。
    
    // 下面是对 rocket 中的内容，颜色，大小的设置
    NSImage *sourc = [NSImage imageNamed:@"FFRing"];
    rocket.contents = (id) [self NSImageToCGImageRef:sourc];
    rocket.scale = 0.2;
    rocket.color = [NSColor redColor].CGColor;//[[UIColor redColor] CGColor];
    rocket.greenRange = 1.0;
    rocket.redRange = 1.0;
    rocket.blueRange = 1.0;
    rocket.spinRange = M_PI; // 子旋转角度范围
    
    /**
     * 添加爆炸的效果，突然之间变大一下的感觉
     */
    CAEmitterCell* burst = [CAEmitterCell emitterCell];
    burst.birthRate = 1.0;
    burst.velocity = 0;
    burst.scale = 2.5;
    burst.redSpeed =-1.5;
    burst.blueSpeed =+1.5;
    burst.greenSpeed =+1.0;
    burst.lifetime = 0.35;
    
    /**
     *  添加星星扩散的粒子
     */
    CAEmitterCell* spark = [CAEmitterCell emitterCell];
    spark.birthRate = 400;
    spark.velocity = 125;
    spark.emissionRange = 2* M_PI;
    spark.yAcceleration = 75; //粒子y方向的加速度分量
    spark.lifetime = 3;
    
    NSImage *star = [NSImage imageNamed:@"FFTspark"];
    spark.contents = (id) [self NSImageToCGImageRef:star];
    spark.scaleSpeed =-0.2;
    spark.greenSpeed =-0.1;
    spark.redSpeed = 0.4;
    spark.blueSpeed =-0.1;
    spark.alphaSpeed =-0.25; // 例子透明度的改变速度
    spark.spin = 2* M_PI; // 子旋转角度
    spark.spinRange = 2* M_PI;
    
    // 将 CAEmitterLayer 和 CAEmitterCell 结合起来
    fireworksEmitter.emitterCells = [NSArray arrayWithObject:rocket];
    //在圈圈粒子的基础上添加爆炸粒子
    rocket.emitterCells = [NSArray arrayWithObject:burst];
    //在爆炸粒子的基础上添加星星粒子
    burst.emitterCells = [NSArray arrayWithObject:spark];
    // 添加到图层上
    [self.congratulations_v.layer addSublayer:fireworksEmitter];
}


- (CGImageRef)NSImageToCGImageRef:(NSImage*)image{
    
    NSData * imageData = [image TIFFRepresentation];
    
    CGImageRef imageRef = NULL;
    
    if (imageData) {
        CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
        imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
    }
    
    return imageRef;
    
}


@end
